// pages/outpatient-fees/outpatient-fees.js
Page({
  data: {
    patientInfo: {
      name: '',
      relation: '本人',
      idNumber: '',
      patientId: null
    },
    showPatientModal: false,
    showTimePicker: false,
    patientList: [],
    expenseList: [
      {
        id: 1,
        feeType: '西药费',
        department: '神经内科',
        doctor: '刘美',
        patient: '蒋峰',
        dateTime: '2020-06-15 11:05',
        amount: '60.00'
      },
      {
        id: 2,
        feeType: '西药费',
        department: '神经内科',
        doctor: '刘美',
        patient: '蒋峰',
        dateTime: '2020-06-15 11:05',
        amount: '60.00'
      },
      {
        id: 3,
        feeType: '西药费',
        department: '神经内科',
        doctor: '刘美',
        patient: '蒋峰',
        dateTime: '2020-06-15 11:05',
        amount: '60.00'
      }
    ],
    filteredExpenseList: [], // 筛选后的费用列表
    // 时间选择器数据
    years: [2020, 2021, 2022, 2023, 2024, 2025],
    months: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
    days: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'],
    startPickerValue: [5, 9, 7], // 默认选择2025年10月08日
    endPickerValue: [5, 9, 7], // 默认选择2025年10月08日
    startDate: '2025年10月08日',
    endDate: '2025年10月08日',
    currentSelecting: 'start' // 当前选择的是开始日期还是结束日期
  },

  onLoad(options) {
    console.log('门诊缴费记录页面加载');
    this.loadCurrentPatient();
    this.loadExpenseData();
    // 初始化显示当前年份的记录
    const currentYear = new Date().getFullYear();
    this.filterExpensesByYear(currentYear);
  },

  // 加载当前患者信息
  loadCurrentPatient() {
    // 从后端获取默认就诊人信息
    wx.request({
      url: 'http://localhost:8005/patient/list',
      method: 'GET',
      header: { 'Content-Type': 'application/json' },
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          let list = res.data
          if (typeof list === 'string') {
            try { list = JSON.parse(list) } catch (e) { return }
          }
          if (list.code !== undefined) list = list.data
          if (!Array.isArray(list)) return
          
          // 找到默认就诊人
          const defaultPatient = list.find(p => p.isDefault === 1)
          if (defaultPatient) {
            this.setData({
              patientInfo: {
                name: defaultPatient.name,
                relation: defaultPatient.relationTypeName || '本人',
                idNumber: (defaultPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2'),
                patientId: defaultPatient.id
              }
            })
          } else {
            // 如果没有默认就诊人，使用第一个就诊人
            const firstPatient = list[0]
            if (firstPatient) {
              this.setData({
                patientInfo: {
                  name: firstPatient.name,
                  relation: firstPatient.relationTypeName || '本人',
                  idNumber: (firstPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2'),
                  patientId: firstPatient.id
                }
              })
            }
          }
        }
      }
    })
  },

  // 加载缴费记录数据
  loadExpenseData() {
    wx.showLoading({
      title: '加载中...'
    });

    // 组装查询参数（包含 patientId）
    const params = {
      page: 1,
      pageSize: 20,
      bizType: '门诊缴费',
      biz_type: '门诊缴费'
    };
    const cached = wx.getStorageSync('userInfo') || {};
    const rawPatientId = (this.data.patientInfo && this.data.patientInfo.patientId) || cached.patientId;
    if (rawPatientId) {
      params.patientId = rawPatientId;
      // 兼容后端不同命名
      params.patient_id = rawPatientId;
    }
    console.log('加载缴费记录参数:', params);

    const requestList = (queryParams) => new Promise((resolve) => {
      wx.request({
        url: 'http://localhost:8084/recharge/list',
        method: 'GET',
        data: queryParams,
        header: { 'Content-Type': 'application/json' },
        success: (res) => resolve(res),
        fail: (e) => resolve({ statusCode: 0, error: e })
      })
    })

    const handleResponse = (res) => {
      if (!(res && res.statusCode === 200 && res.data)) return []
      let body = res.data
      if (typeof body === 'string') {
        try { body = JSON.parse(body) } catch (e) { return [] }
      }
      if (body.code !== undefined) {
        if (body.code !== 200) return []
        body = body.data
      }
      let arr = []
      if (Array.isArray(body)) arr = body
      else if (body && Array.isArray(body.records)) arr = body.records
      else if (body && Array.isArray(body.data)) arr = body.data
      else if (body && Array.isArray(body.list)) arr = body.list
      return this.mapExpenseData(arr)
    }

    // 主请求
    requestList(params).then(async (res) => {
      wx.hideLoading()
      let processed = handleResponse(res)

      // 若无数据且 patientId 可能与订单表相差 10000，则二次尝试 patientId+10000
      if ((!processed || processed.length === 0) && rawPatientId && Number(rawPatientId) < 10000) {
        const altParams = { ...params, patientId: Number(rawPatientId) + 10000, patient_id: Number(rawPatientId) + 10000 }
        console.warn('主请求无数据，尝试 patientId+10000:', altParams.patientId)
        const altRes = await requestList(altParams)
        const altProcessed = handleResponse(altRes)
        if (altProcessed && altProcessed.length) {
          processed = altProcessed
        }
      }

      if (processed && processed.length) {
        this.setData({ expenseList: processed })
        const currentYear = new Date().getFullYear()
        this.filterExpensesByYear(currentYear)
        wx.showToast({ title: '数据加载成功', icon: 'success' })
      } else {
        // 最后兜底：按患者直接查询（不分页）
        if (rawPatientId) {
          const pidList = [Number(rawPatientId), Number(rawPatientId) + 10000]
          for (const pid of pidList) {
            const resByPatient = await new Promise((resolve) => {
              wx.request({
                url: `http://localhost:8084/recharge/patient/${pid}`,
                method: 'GET', header: { 'Content-Type': 'application/json' },
                success: (r) => resolve(r), fail: (e) => resolve({ statusCode: 0, error: e })
              })
            })
            const mapped = handleResponse(resByPatient)
            if (mapped && mapped.length) {
              this.setData({ expenseList: mapped })
              const currentYear = new Date().getFullYear()
              this.filterExpensesByYear(currentYear)
              wx.showToast({ title: '数据加载成功', icon: 'success' })
              return
            }
          }
        }
        this.setData({ expenseList: [], filteredExpenseList: [] })
        wx.showToast({ title: '暂无数据', icon: 'none' })
      }
    })
  },

  // 统一映射方法
  mapExpenseData(expenseData) {
    return expenseData.map(item => ({
      id: item.orderId || item.id,
      feeType: item.bizType || item.biz_type || '门诊缴费',
      department: item.deptName || '门诊部',
      doctor: item.doctorName || '医生',
      patient: item.patientName || this.data.patientInfo.name || '蒋峰',
      // 兼容后端时间字段命名（驼峰/下划线）
      rawTime: (item.operateTime || item.createTime || item.operate_time || item.create_time || item.time || ''),
      dateTime: this.formatTime(item.operateTime || item.createTime || item.operate_time || item.create_time || item.time),
      amount: parseFloat(item.amount || 0).toFixed(2)
    }));
  },

  // 已移除对 /outpatient/recharge/list 的兜底尝试，避免 404 日志
  loadExpenseDataFallback(patientId) {
    const tryNoBizType = () => new Promise((resolve) => {
      const p = { page: 1, pageSize: 20 };
      if (patientId) { p.patientId = patientId; p.patient_id = patientId; }
      wx.request({
        url: 'http://localhost:8084/recharge/list',
        method: 'GET', data: p,
        header: { 'Content-Type': 'application/json' },
        success: (res) => resolve(res), fail: (e) => resolve({ statusCode: 0, error: e })
      })
    });

    const tryOutpatientPrefix = () => new Promise((resolve) => {
      const p = { page: 1, pageSize: 20, biz_type: '门诊缴费', bizType: '门诊缴费' };
      if (patientId) { p.patientId = patientId; p.patient_id = patientId; }
      wx.request({
        url: 'http://localhost:8084/outpatient/recharge/list',
        method: 'GET', data: p,
        header: { 'Content-Type': 'application/json' },
        success: (res) => resolve(res), fail: (e) => resolve({ statusCode: 0, error: e })
      })
    });

    const tryByPatient = () => new Promise((resolve) => {
      if (!patientId) return resolve({ statusCode: 404 });
      wx.request({
        url: `http://localhost:8084/recharge/patient/${patientId}`,
        method: 'GET', header: { 'Content-Type': 'application/json' },
        success: (res) => resolve(res), fail: (e) => resolve({ statusCode: 0, error: e })
      })
    });

    Promise.all([tryNoBizType(), tryOutpatientPrefix(), tryByPatient()]).then((results) => {
      let data = null;
      for (const res of results) {
        if (res && res.statusCode === 200 && res.data) {
          let body = res.data;
          if (typeof body === 'string') {
            try { body = JSON.parse(body); } catch (_) {}
          }
          if (body && body.code !== undefined) { body = body.code === 200 ? body.data : null; }
          if (Array.isArray(body)) { data = body; break; }
          if (body && body.records && Array.isArray(body.records)) { data = body.records; break; }
          if (body && body.data && Array.isArray(body.data)) { data = body.data; break; }
          if (body && body.list && Array.isArray(body.list)) { data = body.list; break; }
        }
      }

      const processed = Array.isArray(data) ? this.mapExpenseData(data) : [];
      if (processed.length) {
        this.setData({ expenseList: processed });
        const currentYear = new Date().getFullYear();
        this.filterExpensesByYear(currentYear);
        wx.showToast({ title: '数据加载成功', icon: 'success' });
      } else {
        this.setData({ expenseList: [] , filteredExpenseList: [] });
        wx.showToast({ title: '暂无数据', icon: 'none' });
      }
    });
  },
  
  // 切换就诊人
  switchPatient() {
    // 先加载患者列表
    this.loadPatientList()
  },
  
  // 加载患者列表
  loadPatientList() {
    wx.showLoading({ title: '加载中...' })
    wx.request({
      url: 'http://localhost:8005/patient/list',
      method: 'GET',
      header: { 'Content-Type': 'application/json' },
      success: (res) => {
        wx.hideLoading()
        if (res.statusCode === 200 && res.data) {
          let patientData = res.data
          
          // 处理数据格式
          if (typeof patientData === 'string') {
            try {
              patientData = JSON.parse(patientData)
            } catch (e) {
              console.error('JSON解析失败:', e)
              return
            }
          }
          
          // 处理Result包装的数据
          if (patientData.code !== undefined) {
            if (patientData.code !== 200) {
              console.error('后端返回错误:', patientData.message)
              wx.showToast({
                title: patientData.message || '请求失败',
                icon: 'none'
              })
              return
            }
            patientData = patientData.data
          }
          
          // 提取患者数组
          if (!Array.isArray(patientData)) {
            if (patientData.data && Array.isArray(patientData.data)) {
              patientData = patientData.data
            } else if (patientData.list && Array.isArray(patientData.list)) {
              patientData = patientData.list
            } else if (patientData.patients && Array.isArray(patientData.patients)) {
              patientData = patientData.patients
            } else {
              console.error('数据不是数组格式:', patientData)
              return
            }
          }
          
          // 构建选择列表
          const itemList = patientData.map(patient => 
            `${patient.name || patient.patientName} (${patient.relationTypeName || patient.relationship || '本人'})`
          )
          
          wx.showActionSheet({
            itemList: itemList,
            success: (res) => {
              if (res.tapIndex >= 0 && res.tapIndex < patientData.length) {
                const selectedPatient = patientData[res.tapIndex]
                const patientInfo = {
                  name: selectedPatient.name || selectedPatient.patientName,
                  relation: selectedPatient.relationTypeName || selectedPatient.relationship || '本人',
                  idNumber: selectedPatient.idCardNumber || selectedPatient.idCard || '622*********0909',
                  patientId: selectedPatient.id || selectedPatient.patientId
                }
                
                this.setData({
                  patientInfo: patientInfo
                })
                
                // 重新加载该患者的缴费记录（携带 patientId）
                this.loadExpenseData()
                
                // 可选：缓存 patientId，便于后续页面使用
                const cacheUser = wx.getStorageSync('userInfo') || {}
                wx.setStorageSync('userInfo', { ...cacheUser, patientId: patientInfo.patientId })
                
                wx.showToast({
                  title: '已切换到' + patientInfo.name,
                  icon: 'success'
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: '加载患者列表失败',
            icon: 'none'
          })
        }
      },
      fail: (error) => {
        wx.hideLoading()
        console.error('网络请求失败:', error)
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        })
      }
    })
  },

  // 关闭就诊人模态框
  closePatientModal() {
    this.setData({
      showPatientModal: false
    });
  },

  // 选择就诊人
  selectPatient(e) {
    const patient = e.currentTarget.dataset.patient;
    this.setData({
      patientInfo: {
        name: patient.name,
        relation: patient.relation,
        idNumber: patient.idNumber,
        patientId: patient.id || patient.patientId || null
      },
      showPatientModal: false
    });
    // 重新加载该患者的缴费记录（携带 patientId）
    this.loadExpenseData();
  },

  // 选择时间范围
  selectTimeRange(e) {
    const range = e.currentTarget.dataset.range;
    if (range === 'year') {
      // 显示近一年的记录
      const currentYear = new Date().getFullYear();
      this.filterExpensesByYear(currentYear);
    }
  },

  // 显示时间选择器
  showTimePicker() {
    this.setData({
      showTimePicker: true
    });
  },

  // 关闭时间选择器
  closeTimePicker() {
    this.setData({
      showTimePicker: false
    });
  },

  // 选择开始日期
  selectStartDate() {
    this.setData({
      currentSelecting: 'start'
    });
  },

  // 选择结束日期
  selectEndDate() {
    this.setData({
      currentSelecting: 'end'
    });
  },

  // 确认时间范围
  confirmTimeRange() {
    // 根据选择的时间范围筛选记录
    this.filterExpensesByDateRange();
    this.setData({
      showTimePicker: false
    });
  },

  // 根据年份筛选费用
  filterExpensesByYear(year) {
    const filteredList = this.data.expenseList.filter(item => {
      const source = item.rawTime || item.dateTime || '';
      const match = typeof source === 'string' && source.match(/^(\d{4})/);
      const itemYear = match ? parseInt(match[1], 10) : (new Date(source).getFullYear());
      return itemYear === year;
    });
    this.setData({
      filteredExpenseList: filteredList.length ? filteredList : this.data.expenseList
    });
  },

  // 根据日期范围筛选费用
  filterExpensesByDateRange() {
    const normalize = (s) => s.replace(/年|月/g, '-').replace(/日/g, '');
    const startDate = new Date(normalize(this.data.startDate));
    const endDate = new Date(normalize(this.data.endDate));
    
    const filteredList = this.data.expenseList.filter(item => {
      const itemDate = new Date(item.dateTime);
      return itemDate >= startDate && itemDate <= endDate;
    });
    
    this.setData({
      filteredExpenseList: filteredList
    });
  },

  // 查看费用详情
  viewExpenseDetail(e) {
    const expense = e.currentTarget.dataset.expense;
    wx.navigateTo({
      url: `/pages/payment-success/payment-success?id=${expense.id}&feeType=${encodeURIComponent(expense.feeType)}&department=${encodeURIComponent(expense.department)}&doctor=${encodeURIComponent(expense.doctor)}&patient=${encodeURIComponent(expense.patient)}&amount=${expense.amount}&dateTime=${encodeURIComponent(expense.dateTime)}`
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 时间选择器变化
  onPickerChange(e) {
    const value = e.detail.value;
    const year = this.data.years[value[0]];
    const month = this.data.months[value[1]];
    const day = this.data.days[value[2]];
    
    if (this.data.currentSelecting === 'start') {
      this.setData({
        startDate: `${year}年${month}月${day}日`,
        startPickerValue: value
      });
    } else {
      this.setData({
        endDate: `${year}年${month}月${day}日`,
        endPickerValue: value
      });
    }
  },

  // 格式化时间
  formatTime(timeStr) {
    if (!timeStr) return ''
    const date = new Date(timeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}`
  },

});
